package com.gulimall.cart.intercept;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.StringUtils;
import com.atguigu.common.vo.MemberResp;
import com.gulimall.cart.util.ThreadLocalUtil;
import com.gulimall.cart.vo.UserInfoVO;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.security.auth.login.LoginContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @Description
 * @Author lhj
 * @Date 2024/3/16 14:33
 */
public class CartInterceptor implements HandlerInterceptor {

    /**
     * 执行目标方法之前检查用户是否存在临时身份
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberResp memberResp = (MemberResp) session.getAttribute(AuthServerConstant.LOGIN_USER);
        UserInfoVO userInfoVO = UserInfoVO.builder().isLogin(false).build();
         if (memberResp != null) {
            userInfoVO.setUserId(memberResp.getId());
            userInfoVO.setIsLogin(true);
        }
        //用户登录从cookie中获取设置到userKey
        setUserkey(request, userInfoVO);
        //如果第一次访问购物车，分配一个临时身份
        if (StringUtils.isEmpty(userInfoVO.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoVO.setUserKey(uuid);
        }
        ThreadLocalUtil.set(userInfoVO);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoVO userInfoVO = ThreadLocalUtil.get();
        if (!userInfoVO.getIsLogin()) {
            setCookie(userInfoVO, response);
        }
    }
    private void setCookie(UserInfoVO userInfoVO, HttpServletResponse response) {
        Cookie cookie = new Cookie(CartConstant.CART_TEMP_USER, userInfoVO.getUserKey());
        cookie.setMaxAge(CartConstant.CAT_TEMP_TIMEOUT);
        cookie.setDomain("gulimall.com");
        response.addCookie(cookie);
    }
    
    private static void setUserkey(HttpServletRequest request, UserInfoVO userInfoVO) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (CartConstant.CART_TEMP_USER.equalsIgnoreCase(cookie.getName().trim())) {
                    userInfoVO.setUserKey(cookie.getValue());
                }               
            }
        }
    }
}
